(function($, doc) {
	mui.init({});
	var userinfo = app.getState() || {};
    var uid = userinfo.user_id;
    window.onload = function(){ 	

		mui.plusReady(function(){
			//关闭等待框
			plus.nativeUI.closeWaiting();
			//显示当前页面
			mui.currentWebview.show();
			var width=document.documentElement.clientWidth;
	    	var height=document.documentElement.clientHeight;
	    	document.getElementById('account_pwd').style.width=width+'px';
	    	document.getElementById('account_pwd').style.height=height+'px';
    	
			var trade_id=plus.webview.currentWebview().trade_id;
			mui.ajax({
				url: apiurl + "Trade/get_trade/",
				data: {'trade_id':trade_id,'_token':userinfo.token},
				async: true,
				dataType: 'json',
				crossDomain: true, //强制使用5+跨域
				type: 'get',
				timeout: 10000,
				success: function(res) {
					console.log(JSON.stringify(res));
					if(res.status ==-3){
						mui.toast(res.msg);
						app.out();
						return false;
					} else {
						var obj=res.data;
						if(obj.sk_bank_img && obj.sk_bank_img.indexOf(upurl+'Uploads') !== -1){
							//
						}
						else if(obj.sk_bank_img){
							obj.sk_bank_img=upurl+obj.sk_bank_img;
						}
						
						// 请求成功
						doc.querySelector("#main-data").innerHTML = template('main-template',obj.data);
					}
				},
				error: function(xhr, type, errorThrown) {
					//console.log(JSON.stringify(xhr));
					//console.log(JSON.stringify(type));
					//console.log(JSON.stringify(errorThrown));
					mui.toast('获取数据失败！');
				}
			});


			doc.getElementById('do_post').addEventListener('tap', function() {
				if(doc.getElementById('pinzhen').getAttribute('data-check')==0){
					alert('请上传打款凭证');
					return false;
				}
				document.getElementById('account_pwd').style.display="block";
				document.getElementById('main_content').style.display="block";
				document.getElementById('keyboard').style.display="block";
				var pwd_array=mui('.mui-input-row.mui-password input[type="password"]');
				mui.each(pwd_array,function(index,item){
					if(item.value!=''){
					   	item.value='';
					}
				}) ;
			})
			
			doc.getElementById('close_win').addEventListener('tap', function() {
				document.getElementById('account_pwd').style.display="none";
				document.getElementById('main_content').style.display="none";
				document.getElementById('keyboard').style.display="none";
			})
			
			//点击数字
			mui('#keyboard').on('tap', '.num.data_num', function() {
				var number=this.getAttribute('data-num');
				var pwd_array=mui('.mui-input-row.mui-password input[type="password"]');
				var f=false;
				var pwd='';
				mui.each(pwd_array,function(index,item){
				   if(item.value==''){
				   	   item.value=number;
				   	   return false;
				   }
				}) ;

				mui.each(pwd_array,function(index,item){
				   if(item.value==''){
				   	   f=true;
				   	   return false;
				   }
				   pwd+=item.value;
				}) ;
				
				if(!f){
					//mui.alert('正在后台处理打款...');
					var Info={
						user_id:userinfo.user_id,
						trade_pwd: pwd,
						buy_bank_name: document.getElementById('buy_bank_name').innerHTML,
						buy_bank_card: document.getElementById('buy_bank_card').innerHTML,
						buy_bank_account: document.getElementById('buy_bank_account').innerHTML,
						dk_type: "",/*document.getElementById('etype').value,*/
						img: document.getElementById("pinzhen").src,
						tid: trade_id,
						_token:userinfo.token
					}
					document.getElementById('account_pwd').style.display="none";
					document.getElementById('main_content').style.display="none";
					document.getElementById('keyboard').style.display="none";
					mui.ajax({
						url: apiurl + "Trade/do_remit/",
						data: Info,
						async: true,
						dataType: 'json',
						crossDomain: true, //强制使用5+跨域
						type: 'post',
						timeout: 10000,
						success: function(res) {
							console.log(JSON.stringify(res));
							if(res.status ==-3){
								mui.toast(res.msg);
								app.out();
								return false;
							}
							// 请求成功
							if(res.status ==0) {
								mui.alert(res.msg);
							} else {
								mui.toast('确认打款成功');
						        mui.fire(plus.webview.getWebviewById('order.html'), 'refresh_data');
				                //mui.fire(plus.webview.getWebviewById('remit.html'), 'refresh_data');
				                mui.back();
							}
						},
						error: function(xhr, type, errorThrown) {
							//console.log(JSON.stringify(xhr));
							//console.log(JSON.stringify(type));
							//console.log(JSON.stringify(errorThrown));
							mui.toast('操作失败！');
						}
					});
				}
			   
			})
			
			
			//点击删除
			mui('#keyboard').on('tap', '#numC', function() {
			     var pwd_array=mui('.mui-input-row.mui-password input[type="password"]');
				 var len=pwd_array.length;
				 for(i=len-1;i>=0;i--){
				 	if(pwd_array[i].value!=''){
				 		pwd_array[i].value='';
				 		break;
				 	}
				 }
			});
			
            mui('body').on('tap', '.mui-popover-action li>a', function() {
				var a = this,
					parent;
				//根据点击按钮，反推当前是哪个actionsheet
				for (parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
					if (parent.classList.contains('mui-popover-action')) {
						break;
					}
				}
				//关闭actionsheet
				mui('#' + parent.id).popover('toggle');
				if(a.getAttribute('id')=='xiangce'){
					//从相册选择
					galleryImg();
					return false;
				}
				if(a.getAttribute('id')=='paizao'){
					//拍照
					getImage();
					return false;
				}
			})
		
			//拍照
			function getImage() {
				var c = plus.camera.getCamera();
				c.captureImage(function(e) {
					plus.io.resolveLocalFileSystemURL(e, function(entry) {
						var s = entry.toLocalURL() + "?version=" + new Date().getTime();
						console.log(s);
						uploadImg(s);
						//document.getElementById("head-img1").src = s;
						//变更大图预览的src
						//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
						document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
					}, function(e) {
						console.log("读取拍照文件错误：" + e.message);
					});
				}, function(s) {
					console.log("error" + s);
				}, {
					filename: "_doc/head.jpg"
				})
			}
			
			
			//相册
			function galleryImg() {
				plus.gallery.pick(function(a) {
					plus.io.resolveLocalFileSystemURL(a, function(entry) {
						plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
							root.getFile("head.jpg", {}, function(file) {
								//文件已存在
								file.remove(function() {
									console.log("file remove success");
									entry.copyTo(root, 'head.jpg', function(e) {
											var e = e.fullPath + "?version=" + new Date().getTime();
											//document.getElementById("pinzhen").src = e;
											uploadImg(e);
											//document.getElementById("head-img1").src = e;
											//变更大图预览的src
											//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
											document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
										},
										function(e) {
											console.log('copy image fail:' + e.message);
										});
								}, function() {
									console.log("delete image fail:" + e.message);
								});
							}, function() {
								//文件不存在
								entry.copyTo(root, 'head.jpg', function(e) {
										var path = e.fullPath + "?version=" + new Date().getTime();
										document.getElementById("pinzhen").src = path;
										//document.getElementById("head-img1").src = path;
										//变更大图预览的src
										//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
										document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
									},
									function(e) {
										console.log('copy image fail:' + e.message);
									});
							});
						}, function(e) {
							console.log("get _www folder fail");
						})
					}, function(e) {
						console.log("读取拍照文件错误：" + e.message);
					});
				}, function(a) {}, {
					filter: "image"
				})
			}
	
	
		function uploadImg(path) {
			var img = new Image();
			img.src = path;
			img.onload = function() {
				var that = this;
				//生成比例 
				var w = that.width,
					h = that.height,
					scale = w / h;
				w = 480 || w; //480  你想压缩到多大
				h = w / scale;
		
				//生成canvas
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				canvas.setAttribute('width', w);
				canvas.setAttribute('height', h);
				ctx.drawImage(that, 0, 0, w, h);
				var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
				console.log(base64);
				//base64 = base64.replace('data:image/jpeg;base64,', '');
				mui.post(uploadurl, {
					file: base64,
					uid: uid,
					path : path,
					name : 'trade',
					pid : trade_id
				}, function(res) {
					console.log(JSON.stringify(res));
					if(res.status > 0) {
						//var img_path=serverurl + 'Uploads/trade/' + trade_id + '.jpg';
						var img_path = res.url;
						document.getElementById("pinzhen").src = img_path;
						mui.toast('上传成功！');
						//userinfo.evidence = serverurl + 'upload/trade/' + tid + '.jpg';
	                     document.getElementById("pinzhen").setAttribute('data-check',1);
					}
				},'json');
		
			}
		}
		
		
	 });

   }
    
    

}(mui, document));

//联系他
function do_tel(phone){
	if(mui.os.plus) {
		plus.device.dial(phone);
	} else {
		location.href = 'tel:' + phone;
	}
}

function see_qrcode(bank_img){
	//打开收款人二维码页
	mui.openWindow({
		id: 'qrcode.html',
		url: '/pages/setting/qrcode.html',
		extras:{
	      img_path: bank_img//自定义扩展参数，可以用来处理页面间传值
	    },
		show: {
			aniShow: 'pop-in'
		},
		waiting: {
			autoShow: false
		}
	});
}

/*
function set_bank(name,card,etype,account){
	document.getElementById('selected_info').innerHTML='已选择：'+name+'&nbsp;&nbsp;'+card;
	document.getElementById('buy_bank_name').value=name;
	document.getElementById('buy_bank_card').value=card;
	document.getElementById('etype').value=etype;
	document.getElementById('buy_bank_account').value=account;  
	document.querySelector('#select_dktype .mui-table-view li').className="mui-table-view-cell mui-collapse";
}*/
